package scrolls;

import java.awt.AlphaComposite;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JPanel;
import javax.swing.Timer;

@SuppressWarnings("serial")
public class Draw extends JPanel implements ActionListener
{
	Player player;
	Timer time;
	Map map;
	Input input;
	long nextSecond = System.currentTimeMillis() + 1000;
	int frameInLastSecond = 0;
	int framesInCurrentSecond = 0;
	float alpha = 0.0f;

	public Draw()
	{
		player = new Player();
		map = new Map();
		input = new Input();
		setFocusable(true);
		addKeyListener(new Input());
		addMouseListener(new Input());
		addMouseMotionListener(new Input());
		time = new Timer(8, this);
		time.start();
	}

	public void actionPerformed(ActionEvent e)
	{
		fps();
		if (!Combat.checkComat())
		{
			Resources.counter();
			player.move();
			Player.mapPosition();
		}
		repaint();
	}

	public void paint(Graphics g)
	{
		super.paint(g);
		Graphics2D g2d = (Graphics2D) g;
		if (!Combat.checkComat())
			paintNonCombat(g2d);
		else if (Combat.checkComat())
			Combat.paintCombat(g2d);
		paintHud(g2d);
		g2d.drawString(frameInLastSecond + " fps", 20, 20);
		g2d.dispose();
		g.dispose();
	}

	private void fadeIn()
	{
		alpha += 0.001f;
		if (alpha >= 1.0f)
		{
			alpha = 1.0f;
		} else
		{
			repaint();
		}
	}

	private void paintNonCombat(Graphics2D g2d)
	{
		g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, alpha));
		g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
		map.drawLevel(g2d);
		g2d.drawImage(player.getPlayerImage(), player.getX(), player.getY(), this);
		g2d.setColor(Color.WHITE);
		fadeIn();
	}

	private void paintHud(Graphics2D g2d)
	{
		HUD.drawHUD(g2d);
		Inventory.collision(g2d);
		map.collision(g2d);
	}

	private void fps()
	{
		long currentTime = System.currentTimeMillis();
		if (currentTime > nextSecond)
		{
			nextSecond += 1000;
			frameInLastSecond = framesInCurrentSecond;
			framesInCurrentSecond = 0;
		}
		framesInCurrentSecond++;
	}

}
